package com.bigmodel.taskmanager;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bigmodel.baidu.BaiduWenXin;
import com.bigmodel.baidu.Chatglm2;
import com.bigmodel.baidu.MarkdownUtil;
import com.bigmodel.util.FtlUtil;
import com.bigmodel.vo.RequestAmdbAttrVO;
import org.junit.Test;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TaskService2 {

    private final static String TASK_LIST_ATTR_NAME = "任务";
    private final static String TASK_ATTR_ID = "任务ID";
    private final static String TASK_ATTR_TOOL = "工具";
    private final static String TASK_ATTR_INPUT = "输入";
    private final static String TASK_ATTR_OPERATION = "操作";
    private final static String TASK_ATTR_OBSERVE = "观察结果";
    private final static String TASK_ATTR_DESCRIBE = "任务描述";

    private final static String BASE_URL = "http://localhost:8888/api";

    /**
     * 执行任务
     */
    public void execute(String faultInfo, List<Task> historyTaskList) {
        HashMap<String, Object> onceMemory = new HashMap<>();

        Task task = new Task();
        task.setTaskTool(ToolEnum2.executeDiskError.getName());
        task.setTaskContent(faultInfo);


        /*-----------step4 遍历执行任务队列-------------*/
        while (task != null && ObjectUtil.isNotEmpty(task.getTaskTool())) {

            for(Task historyTask : historyTaskList){
                if(historyTask.getTaskTool().equals(task.getTaskTool())&&historyTask.getInputParam().equals(task.getInputParam())){
                    System.out.println();
                    System.out.println();
                    System.out.println("AI AGENT: 任务重复-立即终止[" + task.getTaskContent() + "]");
                    break;
                }
            }
            historyTaskList.add(task);

            System.out.println();
            System.out.println();
            System.out.println();
            System.out.println("AI AGENT: ========================================开始执行新任务==========================================");
            System.out.println("AI AGENT: 我准备做以下任务," + task.getTaskContent());
            System.out.println("AI AGENT: 任务信息-使用工具[" + task.getTaskTool() + "]");
            System.out.println("AI AGENT: 任务信息-输入参数[" + task.getInputParam() + "]");

            String response = "";
            try {
                if (ToolEnum2.executeDiskError.getName().equals(task.getTaskTool())) {
                    response = "我当前未执行任何任务，只有故障信息:" + faultInfo;
                } else if (ToolEnum2.findInstance.getName().equals(task.getTaskTool())) {
                    JSONObject jsonObject = JSONUtil.parseObj(task.getInputParam());
                    response = findInstance(jsonObject.getStr("systemName"));
                    response = "我使用" + task.getTaskTool() + "得到结果：" + response;
                    System.out.println("AI AGENT: 执行结果-" + response);
                } else if (ToolEnum2.getInstanceStatus.getName().equals(task.getTaskTool())) {
                    JSONObject jsonObject = JSONUtil.parseObj(task.getInputParam());
                    response = getInstanceStatus(jsonObject.getJSONArray("name").toList(String.class));
                    response = "我使用" + task.getTaskTool() + "得到结果：" + response;
                    System.out.println("AI AGENT: 执行结果-" + response);
                } else if (ToolEnum2.restartInstance.getName().equals(task.getTaskTool())) {
                    JSONObject jsonObject = JSONUtil.parseObj(task.getInputParam());
                    response = restartInstance(jsonObject.getJSONArray("name").toList(String.class));
                    response = "我使用" + task.getTaskTool() + "得到结果：" + response;
                    System.out.println("AI AGENT: 执行结果-" + response);
                } else if (ToolEnum2.findDB.getName().equals(task.getTaskTool())) {
                    JSONObject jsonObject = JSONUtil.parseObj(task.getInputParam());
                    response = findDB("业务分析系统");
                    response = "我使用" + task.getTaskTool() + "得到结果：" + response;
                    System.out.println("AI AGENT: 执行结果-" + response);
                } else if (ToolEnum2.getDbStatus.getName().equals(task.getTaskTool())) {
                    JSONObject jsonObject = JSONUtil.parseObj(task.getInputParam());
                    response = getDbStatus(jsonObject.getJSONArray("name").toList(String.class));
                    response = "我使用" + task.getTaskTool() + "得到结果：" + response;
                    System.out.println("AI AGENT: 执行结果-" + response);
                } else if (ToolEnum2.restartDb.getName().equals(task.getTaskTool())) {
                    JSONObject jsonObject = JSONUtil.parseObj(task.getInputParam());
                    response = restartDb(jsonObject.getJSONArray("name").toList(String.class));
                    response = "我使用" + task.getTaskTool() + "得到结果：" + response;
                    System.out.println("AI AGENT: 执行结果-" + response);
                }


                task.setResult(response);

                /*-----------------------询问下个任务--------------------------------*/
                Map<String, Object> map = new HashMap<>();
                map.put("faultInfo", faultInfo);
                map.put("currentDescribe", response);
                String questionContent = FtlUtil.generateContent(map, "autotask/v2/questionNextTask.ftl");
                String answerContent = Chatglm2.chat(questionContent);

                /*-----------------------得到回复后组装下个任务--------------------------------*/
                if (ObjectUtil.isNotEmpty(answerContent)) {
                    try {
                        JSONObject taskObj = JSONUtil.parseObj(answerContent);
                        task = new Task();
                        task.setTaskContent(taskObj.getStr(TASK_ATTR_DESCRIBE));
                        task.setTaskTool(taskObj.getStr(TASK_ATTR_TOOL));
                        task.setInputParam(taskObj.getJSONObject(TASK_ATTR_INPUT).toString());
                        historyTaskList.add(task);
                    } catch (Exception e) {
                        e.printStackTrace();
                        task = null;
                    }
                } else {
                    task = null;
                }

            } catch (Exception e) {
                e.printStackTrace();
                break;
            }

        }

    }


    public static void main(String[] args) {
        TaskService2 taskService = new TaskService2();
        List<Task> historyTaskList = new ArrayList<>();
        taskService.execute("业务分析系统请求成功率低于100%", historyTaskList);

        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println("============================执行结果==============================");
        for (Task historyTask : historyTaskList) {
            System.out.println("任务信息:" + historyTask.getTaskContent());
            System.out.println("执行结果:" + historyTask.getResult());
        }
    }


    public String getDbStatus(List<String> nameList) {
        String url = BASE_URL + "/testv2/getDbStatus";
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(nameList));

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/getDbStatus.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }


    public String restartDb(List<String> nameList) {
        String url = BASE_URL + "/testv2/restartDb";
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(nameList));

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/restartDb.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }

    @Test
    public void restartDb() {
        List<String> nameList = new ArrayList<>();
        nameList.add("数据库1");
        String url = BASE_URL + "/testv2/restartDb";
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(nameList));

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/restartDb.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        System.out.println(answerContent);
    }


    public String getInstanceStatus(List<String> nameList) {
        String url = BASE_URL + "/testv2/getInstanceStatus";
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(nameList));

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/getInstanceStatus.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }


    public String findInstance(String systemName) {
        String url = BASE_URL + "/testv2/findInstance?systemName=" + systemName;
        String result = HttpUtil.get(url);

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/findInstance.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }

    public String restartInstance(List<String> nameList) {
        String url = BASE_URL + "/testv2/restartInstance";
        String result = HttpUtil.get(url);

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        map.put("instanceName", "adminCenter");
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/restartInstance.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }

    @Test
    public void restartInstance() {
        List<String> nameList  = new ArrayList<>();
        nameList.add("实例1");
        nameList.add("实例2");
        String url = BASE_URL + "/testv2/restartInstance";
        String result = HttpUtil.post(url,JSONUtil.toJsonStr(nameList));

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        map.put("instanceName", "adminCenter");
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/restartInstance.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        System.out.println(answerContent);
    }


    public String findDB(String systemName) {
        String url = BASE_URL + "/testv2/findDb?systemName=" + systemName;
        String result = HttpUtil.get(url);

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/findDb.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }


    public String getAttrByAmdbId(RequestAmdbAttrVO amdbAttrVO, HashMap<String, Object> onceMemory) {
        String url = BASE_URL + "/testv2/getAttrByAmdbId";
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(amdbAttrVO));

        JSONObject jsonObject = JSONUtil.parseObj(result);
        JSONObject data = jsonObject.getJSONObject("data");
        onceMemory.put("ip", data.get("ip"));
        onceMemory.put("userName", data.get("userName"));
        onceMemory.put("passWord", data.get("passWord"));

        Map<String, Object> map = new HashMap<>();
        map.put("amdbId", amdbAttrVO.getAmdbId());
        map.put("attrList", JSONUtil.toJsonStr(amdbAttrVO.getAttrList()));
        map.put("apiResponse", result);
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/getAttrByAmdbId.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }


    public String shellLogin(String ip, String userName, String passWord, HashMap<String, Object> onceMemory) {
        String url = BASE_URL + "/testv2/shellLogin?ip=" + ip + "&userName=" + userName + "&passWord=" + passWord;
        String result = HttpUtil.get(url);

        JSONObject jsonObject = JSONUtil.parseObj(result);
        onceMemory.put("sessionId", jsonObject.get("data"));

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/shellLogin.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }


    public String deleteFile(List<String> fileList) {
        String url = BASE_URL + "/testv2/deleteFile";
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(fileList));

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        map.put("instanceName", "adminCenter");
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/deleteFile.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }

    public String shellLogout(String sessionId) {
        String url = BASE_URL + "/testv2/shellLogout?sessionId=" + sessionId;
        String result = HttpUtil.get(url);

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        map.put("instanceName", "adminCenter");
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/shellLogout.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }

    public String findLog(HashMap<String, Object> onceMemory) {
        String url = BASE_URL + "/testv2/findLog";
        String result = HttpUtil.get(url);

        onceMemory.put("fileList", JSONUtil.toJsonStr(JSONUtil.parseObj(result).getJSONArray("data")));

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        map.put("instanceName", "adminCenter");
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/findLog.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }

    public String findDiskRate(String objectName, HashMap<String, Object> onceMemory) {
        String url = BASE_URL + "/testv2/findDiskRate?objectName=" + objectName;
        String result = HttpUtil.get(url);

        Map<String, Object> map = new HashMap<>();
        map.put("apiResponse", result);
        map.put("objectName", "objectName");
        String questionContent = FtlUtil.generateContent(map, "autotask/v2/findDiskRate.ftl");
        String answerContent = BaiduWenXin.chat(questionContent);
        return answerContent;
    }


    public String receiveQuestion(String questionContent) {


        List<Task> historyTaskList = new ArrayList<>();
        execute(questionContent, historyTaskList);

        StringBuffer stringBuffer = new StringBuffer();
        for (Task historyTask : historyTaskList) {
            stringBuffer.append(historyTask.getTaskContent());
        }

        Map<String, Object> mapReport = new HashMap<>();
        mapReport.put("content", stringBuffer.toString());
        String report = BaiduWenXin.chat(FtlUtil.generateContent(mapReport, "autotask/v2/createReport.ftl"));
        System.out.println("AI AGENT: 最终报告:" + report);
        return report;

    }
}
